<?php
/**
 * Created by PhpStorm.
 * User: Mr.Li <lhb2002@qq.com>
 * Date: 2019/5/28
 * Time: 15:42
 */
namespace LHB_Dycdp\Gateways;

use AlibabaCloud\Client\AlibabaCloud;
use LHB_Dycdp\Exception;

abstract class Gateway
{
    protected $accessKeyId ;
    protected $accessKeySecret ;
    protected $rpc;
    public function __construct($accessKeyId,$accessKeySecret)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->init();
    }

    /**
     * 初始化请求参数
     * User: Mr.Li <lhb2002@qq.com>
     * Date: 2019/5/28
     * Time: 15:53
     */
    protected function init(){
        AlibabaCloud::accessKeyClient($this->accessKeyId,$this->accessKeySecret)->asDefaultClient();
        $this->rpc = AlibabaCloud::rpc();
        $this->rpc->regionId('cn-hangzhou')
                ->product("Dycdpapi")
                ->version("2018-06-10")
                ->action($this->getAction())
                ->method('POST');
    }

    /**
     * 获取当前操作方法
     * @return string
     * User: Mr.Li <lhb2002@qq.com>
     * Date: 2019/5/28
     * Time: 15:47
     */
    abstract public function getAction():string ;

    /**
     * 执行处理
     * @return mixed
     * User: Mr.Li <lhb2002@qq.com>
     * Date: 2019/5/28
     * Time: 15:50
     */
    abstract public function handle($query);

    /**
     * 设置请求的扩展参数
     * @param array $paras
     * User: Mr.Li <lhb2002@qq.com>
     * Date: 2019/5/28
     * Time: 15:57
     */
    protected function setParameters(Array $paras=[] ){
        foreach ( $paras as $key => $val ){
            $methodName = 'with' . ucfirst($key);
            $this->rpc->$methodName($val);
        }
    }

    public function request(){

        $result = $this->rpc->request()->toArray();
        //记录日志
        file_put_contents('log.log',\GuzzleHttp\json_encode($result) . PHP_EOL,FILE_APPEND);
        if('OK'!=$result['Code']){
            throw new Exception($result['Message']);
        }
        return $result;
    }


}